# -*- coding:utf-8 -*-
import json

# @Time    : 2023/5/16 02:21
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @File    : generate_bot_dialogue.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import pandas as pd
import asyncio
from bot.insurance_consultant_dx.sales import Sales
from bot.insurance_consultant_dx.user import User
import uuid
from data_generate import utils
import traceback
import random
from loguru import logger


# 用户query模拟生成
async def mock_bot_dialogue_by_query(path, csv):
    df = pd.read_csv(csv, encoding='utf-8')
    datas = df.to_dict('records')[30:40]
    train_data = []
    out_writer = open("dialogue_tmp.txt", 'a+')
    for data in datas:
        # customer_id,session_id,语音识别文本,,性别,称呼,,地区,,
        name = data['姓名']
        age = data['年龄']
        purpose = data['总结']
        user_content = data['用户话术']
        logger.info('purpose is {purpose}', purpose=purpose)

        try:
            bot = Sales()
            context = []
            instruct_dict_new = {}
            session_id = str(uuid.uuid1())
            instruct_dict_new["id"] = session_id
            instruct_dict_new["messages"] = []
            # instruct_dict_new["messages"].append()
            user_base_info = f"姓名:{name}\n年龄:{str(age)}"
            base_info = f"姓名:{name}\n年龄:{str(age)}"
            logger.info('user base info is {user_base_info}', user_base_info=user_base_info)

            history = bot.format_conversation_history(context)
            res = await bot.async_reply(history, session_id, name, user_base_info)
            conversation_dict = {}
            conversation_dict["role"] = "assistant"
            conversation_dict["content"] = res
            instruct_dict_new["messages"].append(conversation_dict)
            context.append(conversation_dict)

            for j in range(50):
                bot = Sales()
                history = bot.format_conversation_history(context)
                user = User(user_base_info, history, purpose, user_content=user_content)
                query = await user.achat_with_proxy_gpt4(save_data=False)
                conversation_dict = {}
                conversation_dict["role"] = "user"
                conversation_dict["content"] = query.strip()
                instruct_dict_new["messages"].append(conversation_dict)
                context.append(conversation_dict)
                mute_count = 0
                for conversation in context:
                    if conversation['role'] == 'user' and conversation['content'] == '@@quiet@@':
                        mute_count += 1
                if mute_count >= 3:
                    res = '那等您方便的时候我们再联系吧，祝您生活愉快，再见！'
                elif query == '@@quiet@@':
                    res = '抱歉哈，没太听清楚，您是本人吗？'
                else:
                    res = await bot.async_reply(context, session_id, name, base_info, content=query.strip())
                    conversation_dict = {}
                conversation_dict["role"] = "assistant"
                conversation_dict["content"] = res
                instruct_dict_new["messages"].append(conversation_dict)
                context.append(conversation_dict)
                logger.info('上下文缓存是 {context}', context=json.dumps(context))
                # history = bot.format_conversation_history(context)

                # user_suggestion_obj = UserSuggestion(conversation_history=history)
                # user_suggestion = await user_suggestion_obj.achat_auto_llm()
                # print(user_suggestion)

                if "再见" in res or "您不要挂电话，马上为您服务" in res or "祝您生活愉快" in res:
                    break
            train_data.append(instruct_dict_new)
            utils.jdump(train_data, path)
            out_writer.write(str(instruct_dict_new) + "\n")
            out_writer.flush()
        except Exception as e:
            traceback.print_exc()
            # 打印堆栈
            print(e)

    out_writer.close()

def conversation2csv(file_path):
    datas = utils.jload(file_path)
    df = pd.DataFrame(columns=['角色', '内容'])

    for data in datas:
        messages = data['messages']
        for text in messages:
            df = df._append(
                {"角色": text['role'],
                 "内容": text['content']},
                ignore_index=True)
        df = df.reset_index(drop=True)._append(
            {"角色": "",
             "内容": ""},
            ignore_index=True)
    df.to_csv(file_path.replace('.json', '.csv'))


if __name__ == '__main__':
    import datetime

    now_date = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
    now_date = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
    file_path = "../data_set/bot_dialogue/bot_dialogue_" + now_date + ".json"
    csv = "../internal_server/bot/insurance_consultant_dx/data/用户信息和对话-总结.csv"  # 文件夹路径
    asyncio.run(mock_bot_dialogue_by_query(file_path, csv))
    conversation2csv(file_path)

    # get_faq_corpus("/Users/cy/Downloads/222.csv")
